package com.yy.Comtroller;

import com.yy.entity.User;
import com.yy.mapper.UserMapper;
import com.yy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login.do")
public class UserLoginController extends BaseController {
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SqlSession sqlSession= MybatisUtils.getSqlSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        User user1 = userMapper.selectUserById(user);
        if (user1!=null){
            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("success.jsp").forward(request,response);
        }else {
            request.setAttribute("error","用户名密码错误");
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        SqlSession sqlSession= MybatisUtils.getSqlSession();

        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        int i=userMapper.insertUserById(user);
        if(i>0){
            request.getSession().setAttribute("user",user);
            response.sendRedirect("index.jsp");
        }
    }
}
